package com.me.chat.util.img;

import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * Webp图片格式工具类
 * @Author: qiu
 * @Date: 2021/2/23 19:01
 */
public class WebpUtil {

    //转换的资源类型
    public static final String WEBP = "webp";


    /**
     * MultipartFile转为byte数组
     * ByteArrayOutputStream好处在于当write的时候不会本地生成额外文件 ，将内容写入输出流里
     * @param file
     * @return
     */
    public static ByteArrayOutputStream toWebpFile(MultipartFile file){

        ByteArrayOutputStream output = null;
        try {
            output = new ByteArrayOutputStream();
            //将MultipartFile内容读出来
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            //将内容写进字节输出流
            ImageIO.write(bufferedImage, WEBP, output);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
           if(output != null){
               try {
                   output.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
        }
        return output;
    }
}
